import { getArticleList, getNewList } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleItem from '../ArticleItem'

import styles from './index.module.scss'

type ArticleListProps = {
  channelId: number
}

const ArticleList = ({ channelId }: ArticleListProps) => {
  const dispatch = useDispatch()

  const history = useHistory()

  const { channelArticles } = useSelector((state: RootState) => state.home)

  const { articles = [], timestamp } = channelArticles[channelId] || {}

  return (
    <div className={styles.root}>
      <PullToRefresh
        onRefresh={async () => {
          await dispatch(getNewList(channelId, Date.now().toString()))
        }}
      >
        {/* 文章列表中的每一项 */}
        {articles.map((item) => (
          <div
            key={item.art_id}
            className="article-item"
            onClick={() => {
              history.push(`/article/${item.art_id}`)
            }}
          >
            <ArticleItem article={item} />
          </div>
        ))}
        <InfiniteScroll
          // 1.决定触底时是否执行loadMore
          hasMore={timestamp !== null}
          // 2.触底时要执行的加载数据的逻辑
          loadMore={async () => {
            // await console.log('在请求')
            await dispatch(
              getArticleList(channelId, timestamp || Date.now().toString())
            )
          }}
        />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
